package com.wangjw.seckill.service;

import com.wangjw.seckill.dao.MiaoshaUserDao;
import com.wangjw.seckill.domain.MiaoshaUser;
import com.wangjw.seckill.result.CodeMsg;
import com.wangjw.seckill.result.Result;
import com.wangjw.seckill.util.MD5Util;
import com.wangjw.seckill.util.ValidatorUtil;
import com.wangjw.seckill.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by wangjw on 18/1/11.
 */
@Service
public class MiaoshaUserService {

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;

    public Result<String> login(LoginVo loginVo) {
        if (loginVo == null) {
            return Result.error(CodeMsg.SERVER_ERROR);
        }

        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        if (StringUtils.isEmpty(mobile)) {
            return Result.error(CodeMsg.MOBILE_EMPTY);
        }

        if (!ValidatorUtil.isMobile(mobile)) {
            return Result.error(CodeMsg.MOBILE_ERROR);
        }

        if (StringUtils.isEmpty(password)) {
            return Result.error(CodeMsg.PASSWORD_EMPTY);
        }

        MiaoshaUser miaoshaUser = miaoshaUserDao.getById(Long.parseLong(mobile));
        if (miaoshaUser == null) {
            return Result.error(CodeMsg.MOBILE_NOT_EXIST);
        } else {
            String dbPassword = miaoshaUser.getPassword();
            String dbSalt = miaoshaUser.getSalt();
            if (!dbPassword.equals(MD5Util.formPassToDBPass(password, dbSalt))) {
                return Result.error(CodeMsg.PASSWORD_ERROR);
            }
            return Result.success("登录成功");
        }
    }
}
